#! /usr/bin/python3
# -*- coding: UTF-8 -*-

if __name__ == "__main__":
	raise Exception("不支持从这里调用")

__version__ = "1.0"
__all__ = []

from uuid import uuid4

from com.mousechsh.business.lib.MouseChshAuthorizationAnnotition import MouseChshRemoteAuthorizationAnnotition
from com.mousechsh.business.lib.model.MouseChshDomainModel import MouseChshDomainModel
from com.mousechsh.business.lib.model.MouseChshKeyValueModel import MouseChshKeyValueModel
from com.mousechsh.business.lib.model.MouseChshUserModel import MouseChshUserModel
from com.mousechsh.common.data.MouseChshDao import MouseChshDao
from com.mousechsh.common.data.MouseChshData import mousechsh_data_merge
from com.mousechsh.common.data.json.MouseChshJson import mousechsh_json_to_json
from com.mousechsh.common.io.db.MouseChshPostgresql import MouseChshPostgresql
from com.mousechsh.common.middle.http.MouseChshHttpHeader import mousechsh_http_header_accept_language_annotation
from com.mousechsh.common.middle.rest_api.MouseChshRestApi import mousechsh_rest_api_annotation
from com.mousechsh.common.middle.router.MouseChshCorsAnnotition import mousechsh_cors_annotation
from com.mousechsh.common.middle.router.MouseChshHttpRouter import mousechsh_http_router_annotation
from com.mousechsh.common.util.MouseChshDateTime import MouseChshDateTime


@mousechsh_http_router_annotation(method=['POST', 'OPTIONS'], path='/user/add')
@mousechsh_cors_annotation()
@mousechsh_http_header_accept_language_annotation()
@MouseChshRemoteAuthorizationAnnotition()
@mousechsh_rest_api_annotation()
def _addUser(params):
	lang = params.get('lang', 'zh-cn')
	user = MouseChshUserModel()
	user.set_data(params)
	user.Id = str(uuid4()).upper()
	db = MouseChshPostgresql()
	db.connect()
	db.execute(
		'''
	   INSERT INTO "A_AD"."T_User"(
		   "C_Id",
		   "C_CrOn",
		   "C_MoOn",
		   "L_Scheme",
		   "X_Data",
		   "C_Name",
		   "L_Domain_Id",
		   "X_Display",
		   "L_UserType",
		   "C_NeekName",
		   "C_Email",
		   "L_AuthMethod",
		   "C_Password")
	   VALUES (
		   %(id)s,
		   %(cron)s,
		   %(moon)s,
		   'User',
		   '{}',
		   %(name)s,
		   %(domain)s,
		   %(display)s,
		   %(type)s,
		   %(neek)s,
		   %(email)s,
		   %(auth)s,
		   %(pwd)s
	   )
		   ''', {
			'id': user.get('Id'),
			'cron': MouseChshDateTime().to_timestamp(),
			'moon': MouseChshDateTime().to_timestamp(),
			'name': user.get('Name'),
			'domain': user.get('Domain'),
			'display': mousechsh_json_to_json(
				{
					lang: user.get('Display'),
					'': lang
				}
			),
			'type': user.get('Type'),
			'neek': user.get('NeekName'),
			'email': user.get('Email'),
			'auth': user.get('AuthMethod'),
			'pwd': user.get('Password'),
		}
	)
	db.commit()
	db.close()
	return user.get('Id')


@mousechsh_http_router_annotation(method=['POST', 'OPTIONS'], path='/user/remove')
@mousechsh_cors_annotation()
@mousechsh_http_header_accept_language_annotation()
@MouseChshRemoteAuthorizationAnnotition()
@mousechsh_rest_api_annotation()
def _removeUser(params):
	user = MouseChshUserModel()
	user.set_data(params)
	db = MouseChshPostgresql()
	db.connect()
	db.execute(
		'''
	   DELETE FROM "A_AD"."T_User"
	   WHERE "C_Id" = %(id)s
		   ''', {
			'id': user.get('Id')
		}
	)
	db.commit()
	db.close()
	return True


@mousechsh_http_router_annotation(method=['POST', 'OPTIONS'], path='/user/update')
@mousechsh_cors_annotation()
@mousechsh_http_header_accept_language_annotation()
@MouseChshRemoteAuthorizationAnnotition()
@mousechsh_rest_api_annotation()
def _updateUser(params):
	lang = params.get('lang', 'zh-cn')
	user = MouseChshUserModel()
	user.set_data(params)
	db = MouseChshPostgresql()
	db.connect()
	data = db.get(
		'''
	   SELECT
		   "C_Id",
		   "C_CrOn",
		   "C_CrBy",
		   "C_MoOn",
		   "C_MoBy",
		   "C_RvOn",
		   "C_RvBy",
		   "C_St",
		   "C_Owner",
		   "C_Flag",
		   "L_Scheme",
		   "X_Data",
		   "X_Property",
		   "C_Name",
		   "L_Domain_Id",
		   COALESCE( "X_Display" ->> %(lang)s, "X_Display" ->> ( "X_Display" ->> '' ) ) AS "C_Display",
		   "L_UserType" AS "C_UserType",
		   "C_NeekName",
		   "C_Email",
		   "L_TrustUser_Id",
		   "L_AuthMethod" AS "C_AuthMethod",
		   "C_Password"
	   FROM "A_AD"."T_User"
	   WHERE "C_Id" = %(id)s
		   ''', {
			'lang': lang,
			'id': user.get('Id')
		}
	)
	db.close()
	dao = MouseChshDao()
	dao.set_model(MouseChshUserModel)
	users = dao.parse(data)
	if len(users) <= 0:
		return
	user = mousechsh_data_merge(users[0], user)
	db = MouseChshPostgresql()
	db.connect()
	db.execute(
		'''
	   UPDATE "A_AD"."T_User" SET
		   "C_MoOn"       = %(moon)s,
		   "L_Scheme"     = 'User',
		   "X_Data"       = '{}',
		   "C_Name"       = %(name)s,
		   "X_Display"    = "X_Display" || %(display)s,
		   "L_UserType"   = %(type)s,
		   "C_NeekName"   = %(neekname)s,
		   "C_Email"      = %(email)s,
		   "L_AuthMethod" = %(auth)s,
		   "C_Password"   = %(pwd)s
	   WHERE "C_Id"       = %(id)s
		   ''', {
			'moon': MouseChshDateTime().to_timestamp(),
			'name': user.get('Name'),
			'domain': user.get('Domain'),
			'display': mousechsh_json_to_json(
				{
					lang: user.get('Display').get(lang, None) if isinstance(
						user.get('Display'), dict
					) else user.get('Display'),
					'': lang
				}
			),
			'type': user.get('Type'),
			'neekname': user.get('NeekName'),
			'email': user.get('Email'),
			'auth': user.get('AuthMethod'),
			'pwd': user.get('Password'),
			'id': user.get('Id')
		}
	)
	db.commit()
	db.close()
	return user.get('Id')


@mousechsh_http_router_annotation(method=['POST', 'OPTIONS'], path='/user/get')
@mousechsh_cors_annotation()
@mousechsh_http_header_accept_language_annotation()
@MouseChshRemoteAuthorizationAnnotition()
@mousechsh_rest_api_annotation()
def _getUser(params):
	lang = params.get('lang', 'zh-cn')
	db = MouseChshPostgresql()
	db.connect()
	data = db.get(
		'''
	   SELECT
		   A."C_Id",
		   A."C_CrOn",
		   A."C_CrBy",
		   A."C_MoOn",
		   A."C_MoBy",
		   A."C_RvOn",
		   A."C_RvBy",
		   A."C_St",
		   A."C_Owner",
		   A."C_Flag",
		   A."L_Scheme",
		   A."X_Data",
		   A."X_Property",
		   A."C_Name",
		   A."L_Domain_Id" AS "C_Domain_Id",
		   A."L_Domain_Id",
		   COALESCE( B."X_Display" ->> %(lang)s, B."X_Display" ->> ( B."X_Display" ->> '' ) ) AS "L_Domain_Display",
		   COALESCE( A."X_Display" ->> %(lang)s, A."X_Display" ->> ( A."X_Display" ->> '' ) ) AS "C_Display",
		   A."X_Display",
		   A."L_UserType" AS "C_UserType",
		   A."L_UserType" AS "L_UserType_Key",
		   COALESCE( C."X_Display" ->> %(lang)s, C."X_Display" ->> ( C."X_Display" ->> '' ) ) AS "L_UserType_Display",
		   A."C_NeekName",
		   A."C_Email",
		   A."L_TrustUser_Id",
		   A."L_AuthMethod" AS "C_AuthMethod",
		   A."L_AuthMethod" AS "L_AuthMethod_Key",
		   COALESCE( D."X_Display" ->> %(lang)s, D."X_Display" ->> ( D."X_Display" ->> '' ) ) AS "L_AuthMethod_Display"
	   FROM "A_AD"."T_User" A
	   INNER JOIN "A_AD"."T_Domain" B
		   ON A."L_Domain_Id"  = B."C_Id"
	   LEFT OUTER JOIN "A_Const"."W_KeyValue" C
		   ON A."L_UserType"   = C."C_Key"
	   LEFT OUTER JOIN "A_Const"."W_KeyValue" D
		   ON A."L_AuthMethod" = D."C_Key"
	   ORDER BY A."C_Order" ASC
	   LIMIT 100
		   ''', {
			'lang': lang
		}
	)
	db.close()
	dao = MouseChshDao()
	dao.set_model(MouseChshUserModel)
	dao.set_extra_model(MouseChshDomainModel)
	dao.set_extra_model(MouseChshKeyValueModel, key='UserType')
	dao.set_extra_model(MouseChshKeyValueModel, key='AuthMethod')
	users = dao.parse(data)
	return users
